package com.java.hohenheim.springplatform.web.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.hohenheim.springplatform.data.exception.ExceptionInfoModel;
import com.java.hohenheim.springplatform.data.exception.ExceptionPackingModel;
import com.java.hohenheim.springplatform.define.ResultCodes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Hohenheim
 * @date 2020/1/14
 * @description HTTP错误处理
 */
@Component
public class PlatformErrorAttributes extends DefaultErrorAttributes {
    public static final String PLATFORM_ERROR_ATTR_KEY = "PLATFORM_ERROR_KEY";

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errInfoMap = super.getErrorAttributes(webRequest, options);
        HashMap<String, Object> errorResultMap = null;

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(errInfoMap);
            ExceptionInfoModel exceptionInfo = objectMapper.readValue(json, ExceptionInfoModel.class);

            //处理错误信息
            String errMsg = exceptionInfo.getMessage();
            if(StringUtils.isNotBlank(errMsg)) {
                String[] msgArray = errMsg.split(":");
                errMsg = msgArray[msgArray.length - 1].trim();
            }

            //封装错误信息
            ExceptionPackingModel packingModel = new ExceptionPackingModel(ResultCodes.REQ_OPT_FAILURE, exceptionInfo);
            packingModel.setMessage(errMsg);

            errorResultMap = new HashMap<>(1);
            errorResultMap.put(PLATFORM_ERROR_ATTR_KEY, packingModel);
        }
        catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if(null != errorResultMap) {
            errInfoMap = errorResultMap;
        }

        return errInfoMap;
    }
}